# ********************************************
# * Statistics Script                        *
# * Authors: André Bannwart Perina           *
# *          Antonio Canabrava Fraideinberze *
# *          Willian Felipe Lopes da Silva   *
# ******************************************** 

import sys
import statistics as stats

if len(sys.argv) != 5:
    print("Usage: python3 stats.py numIters inputPath outputPath beta")
    exit(1)

# Gets all the input parameters and set to the respective variables
numIters = int(sys.argv[1])
inputPath = sys.argv[2]
outputFile = sys.argv[3]
beta = int(sys.argv[4])
generation = int(inputPath.split('/')[1].split('generation')[1])

# This is important for the standard deviation calculus, it must be greater than 1
if numIters <= 1:
    print("numIters has to be greater than one to calculate the standard deviation.")
    exit(1)

timeList = []
distList = []
fitnessList = []

# For all the individuals, get its information and append them in the respective list
for i in range(numIters):
    pIn = open(inputPath + str(i), "r")
    time, dist = pIn.read().split()
    timeList.append(float(time))
    distList.append(float(dist))
    fitnessList.append(beta - (float(time) * float(dist)))
    pIn.close()

# Calculates the mean of each variable
avgTime = stats.mean(timeList)
avgDist = stats.mean(distList)
avgFitness = stats.mean(fitnessList)

# Calculates the standard deviation of each variable
stdevTime = stats.stdev(timeList)
stdevDist = stats.stdev(distList)
stdevFitness = stats.stdev(fitnessList)

# Gets the number of bad and good individuals created
pIn = open("stats/stats", "r")
good, bad = pIn.read().split()
pIn.close()

# Print to the file all the statistics
pOut = open(outputFile, "w")
pOut.write("Time stats: " + str(avgTime) + " " + str(stdevTime) + "\n")
pOut.write("Dist stats: " + str(avgDist) + " " + str(stdevDist) + "\n")
pOut.write("Fitness stats: " + str(avgFitness) + " " + str(stdevFitness) + "\n")
pOut.write("Fisher stats: " + str((stdevFitness * stdevFitness / avgFitness)) + "\n")
pOut.write("Updated Fisher stats: " + str((stdevFitness * stdevFitness / avgFitness) - avgFitness) + "\n")
pOut.write("Individuals: " + good + " " + bad + "\n")
pOut.close()
